<template>
  <BasicTable @register="registerTable">
    <template #headerTop>
      <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
        <template #message>
          <div>
            <span>已选中{{ checkedKeys.length }}条记录</span>
            <div style="position: absolute; top: 4px; right: 10px">
              <Tooltip title="导出widgets">
                <a-button type="text" @click="handleSelectedDownload">
                  <Icon :icon="ICON.DOWNLOAD" color="#0960bd" />
                </a-button>
              </Tooltip>
              <Tooltip title="删除">
                <a-button type="text" @click="handleSelectedDelete">
                  <Icon :icon="ICON.DELETE" color="#0960bd" />
                </a-button>
              </Tooltip>
            </div>
          </div>
        </template>
      </Alert>
    </template>
    <template #toolbar>
      <Dropdown
        :trigger="['click']"
        :dropMenuList="[
          {
            text: '创建新部件',
            icon: ICON.ADDENTITY,
            event: '',
            onClick: () => {
              openAddModal(true);
            },
          },
          {
            text: 'Import widget',
            icon: ICON.IMPORTENTITY,
            event: '',
            onClick: () => {
              openUploadModal(true, { key: 'upload' });
            },
          },
        ]"
      >
        <a-button type="primary">添加部件</a-button>
      </Dropdown>
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <TableAction
          :actions="[
            {
              icon: ICON.EDIT,
              tooltip: {
                title: '编辑',
                placement: 'top',
              },
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: ICON.CHECK,
              tooltip: { title: '详情', placement: 'top' },
              onClick: handleDetail.bind(null, record),
            },
            { icon: ICON.DELETE, tooltip: { title: '删除', placement: 'top' }, disabled: true },
          ]"
          :dropDownActions="[
            {
              icon: ICON.DOWNLOAD,
              onClick: handleDownload.bind(null, record),
              label: '导出部件',
            },
            {
              icon: ICON.EDIT,
              onClick: handleCoding.bind(null, record),
              label: '绘制部件',
            },
          ]"
        />
      </template>
    </template>
  </BasicTable>
  <UploadModal @register="registerUploadModal" @success="handleSuccess" />
  <AddModal @register="registerAddModal" />
  <EditModal @register="registerEditModal" @success="handleSuccess" />
  <PublicDrawer
    @register="registerDrawer"
    @update-desc-data="handleUpdateDescData"
    :showTabs="['detail', 'version']"
  />
</template>
<script setup lang="ts">
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { widgetsTableSchema, searchSchema, detailSchema } from './widgetsTable.data';
  import {
    getWidgets,
    exportWidgets,
    importWidget,
    deleteWidgets,
    editWidgets,
    getWidgetById,
  } from '/@/api/thingsborad/resources/widgets/widgets';
  import { widgetsTableParams } from '/@/api/thingsborad/resources/widgets/widgetsModel';
  import Icon from '/@/components/Icon';
  import { saveAs } from 'file-saver';
  import { Dropdown } from '/@/components/Dropdown';
  import { ICON } from '/@/enums/iconEnum';
  import { Alert, Tooltip } from 'ant-design-vue';
  import UploadModal from './components/UploadModal.vue';
  import { useModal } from '/@/components/Modal';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { ref, onMounted } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSZip from 'jszip';
  import { useRouter } from 'vue-router';
  import AddModal from './components/AddModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useDrawer } from '/@/components/Drawer';
  import EditModal from './components/EditModal.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';

  const router = useRouter();
  const userStore = useUserStore();
  const { createConfirm } = useMessage();
  const checkedKeys = ref<any>([]);
  const [registerTable, { reload, setProps, getSelectRows }] = useTable({
    title: '设备',
    columns: widgetsTableSchema,
    ...tableStyleSetting,
    immediate: false,
    api: getWidgets,
    beforeFetch: (value) => {
      let params: widgetsTableParams = {
        page: value.page - 1,
        pageSize: value.pageSize,
        sortProperty: value.field,
        sortOrder: value.order == 'ascend' ? 'ASC' : 'DESC',
        textSearch: value.textSearch,
        tenantOnly: false,
        fullSearch: false,
        deprecatedFilter: 'ALL',
      };
      return params;
    },
    afterFetch: (res) => {
      res.length != 0
        ? res.forEach((item: any) => {
            item.system = userStore.getUserInfo.customerId.id == item.tenantId.id;
            item.id = item.id.id;
          })
        : null;
      return res;
    },
    fetchSetting: {
      pageField: 'page',
      sizeField: 'pageSize',
      listField: 'data',
      totalField: 'totalElements',
    },
    formConfig: {
      layout: 'horizontal',
      schemas: searchSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 8 },
        lg: { span: 6, offset: 12 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
      getCheckboxProps: (record) => ({
        disabled: record.system,
      }),
    },
  });
  const [registerUploadModal, { openModal: openUploadModal }] = useModal();
  const [registerAddModal, { openModal: openAddModal }] = useModal();
  const [registerEditModal, { openModal: openEditModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();
  // 详情
  const handleDetail = (record: Recordable) => {
    openDrawer(true, {
      entityType: ENTITY_TYPE.WIDGET_TYPE,
      entityId: record.id,
      title: record.name,
      api: getWidgetById,
      detailSchema,
      params: record.id,
    });
  };
  // 抽屉详情数据更改
  const handleUpdateDescData = (value: Recordable) => {
    value.createdTime = value.createdTime;
    value.title = value.name;
    value.image = value.image;
    value.description = value.description;
    value.tags = value.tags;
  };
  // 编辑
  const handleEdit = (record: Recordable) => {
    openEditModal(true, { key: 'edit', record });
  };
  // 下载
  const handleDownload = async (record: Recordable) => {
    const value = await exportWidgets(record.id);
    const jsonBlob = new Blob([JSON.stringify(value)], {
      type: 'application/json',
    });
    saveAs(jsonBlob, `${record.name}.json`);
  };
  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected: boolean, _selectedRows: Recordable, changeRows: Recordable[]) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 多选导出
  const handleSelectedDownload = async () => {
    const dataSource = getSelectRows();
    const zip = new JSZip();
    const folder = zip.folder('widget_types');
    for (const item of checkedKeys.value) {
      const value = await exportWidgets(item);
      const jsonBlob = new Blob([JSON.stringify(value)], {
        type: 'application/json',
      });
      for (const element of dataSource) {
        item == element.id ? folder?.file(element.name + '.json', jsonBlob) : null;
      }
    }
    zip.generateAsync({ type: 'blob' }).then(function (content) {
      saveAs(content, 'widget_types.zip');
    });
  };
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个widget吗？`,
      content: '请注意：确认后，设备及其所有相关数据将不可恢复。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          await deleteWidgets(item);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  };
  const handleCoding = (record: Recordable) => {
    router.push({
      path: '/tb-resources/widgets-coding',
      query: { key: 'edit', widgetId: record.id },
    });
  };

  const handleUploadSubmit = async (data: Recordable) => {
    const { jsonValue: value } = data;
    let params = {
      updateExistingByFqn: Boolean(value.fqn),
      jsonValue: value,
    };
    await importWidget(params);
    reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
  };

  const handleEditSubmit = async (data: Recordable) => {
    await editWidgets(data.record);
    reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
  };

  /**
   *
   * @param key 匹配关键字
   * @param data 对应数据
   */
  const handleSuccess = async (key: string, data: Recordable) => {
    switch (key) {
      case 'upload':
        // 上传部件
        handleUploadSubmit(data);
        break;
      case 'edit':
        // 编辑部件
        handleEditSubmit(data);
        break;
    }
  };

  onMounted(() => {
    reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
  });
</script>
<style lang="less" scoped>
  :deep(.vben-basic-table-form-container .ant-form) {
    padding-left: 0;
    padding-top: 14px;
    padding-bottom: 14px;
  }
</style>
